﻿using Noria.Net.Chaos.Net;
using Noria.Net.Chaos.Properties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace Noria.Net.Chaos
{
    class ChaosService : ServiceBase
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private PortMapper mapper = new PortMapper(Settings.Default.Listen, Settings.Default.Forward, Settings.Default.MaxConcurrency);

        public ChaosService()
        {
            this.ServiceName = Settings.Default.ServiceName;
        }

        internal void Start()
        {
            OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                mapper.StartListen();
                log.Info("PortMapper has been started");
            }
            catch (Exception e)
            {
                log.Error("Failed to start PortMapper", e);
                throw;
            }
        }

        protected override void OnStop()
        {
            try
            {
                log.Info("Stop signal has been received");
                mapper.StopListen();
                mapper.WaitAll();
                log.Info("PortMapper has been stopped");
            }
            catch (Exception e)
            {
                log.Error("Failed to stop PortMapper", e);
            }
            finally
            {
                mapper.Dispose();
                log.Info("PortMapper has been disposed");
            }
        }
    }
}
